<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\index\service;

use app\index\model\Agent;
use app\index\model\AgentApply as admin;
use app\index\model\Configuration;
use app\index\model\User;
use think\Exception;
use think\facade\Db;

class AgentApplyService
{

    private $user;
    private $configuration;

    public function __construct()
    {
        global $user;
        $this->user = $user;
        $configuration = Configuration::where(['type' => "agentExplain"])
            ->where('mall_id',$user['mall_id'])
            ->value("configuration");

        if (!$configuration)
            throw new Exception("未开启分销",HTTP_INVALID);
        $this->configuration = json_decode($configuration,true);

        if (empty($this->configuration['open']))
            throw new Exception("未开启分销",HTTP_INVALID);

//        if ($this->configuration['become']['type'] != 4)
//            throw new Exception("无法通过申请成为分销商,请参考其他条件",HTTP_INVALID);

    }


    public function save(array $data)
    {
        $data['pid'] = isset($this->user['pid']) ?$this->user['pid']:0;
        $data['user_id'] = $this->user['id'];
        $data['mall_id'] = $this->user['mall_id'];
        if($this->configuration['become'] && $this->configuration['become']['type'] !=4){
            throw new Exception("不支持手动申请成为分销商", HTTP_NOTACCEPT);
            return [HTTP_CREATED, "不支持手动申请成为分销商"];
        }
        if (empty($this->configuration['isAudit'])) {
            $data['status'] = 1;
            $agent = Agent::create($data);
            User::update(['agent_id' => $agent->id],['id'=>$this->user['id']]);
            return [HTTP_CREATED, "成功成为分销商"];
        }else {
            $apply = Db::name('agent_apply')
                ->where('user_id',$data['user_id'])
                ->find();
            if (!empty($apply) && $apply['status'] == 0) {
                throw new Exception("已有申请", HTTP_NOTACCEPT);
            }elseif(!empty($apply) && $apply['status'] == 1){
                $agent = Db::name('agent')->where('user_id',$data['user_id'])->find();
                if (!empty($agent) && !empty($agent['delete_time'])){
                    Db::name('agent_apply')
                        ->where('id',$apply['id'])
                        ->update(['status' => 0,'create_time' => now(),'update_time' => now()]);
                    $model = admin::where(['user_id' => $data['user_id'],'status' => 0])->find();
                }else{
                    $model = $apply;
                }
            }elseif(!empty($apply) && $apply['status'] == 2) {
                $data = array_merge(['delete_time' => null, 'status' => 0, 'create_time' => now()],$data);
                Db::name('agent_apply')->where(['user_id' => $data['user_id']])->update($data);
                $model = admin::where(['user_id' => $data['user_id'],'status' => 0])->find();
            }else{
                $model = admin::create($data);
            }
        }
        return [HTTP_CREATED, $model];
    }


    public function read()
    {
        $model = admin::field(['id', 'name', 'mobile', 'create_time', 'status', 'remark'])
            ->order("id", "desc")
            ->where(['user_id' => $this->user['id']])
            ->find();
        return [HTTP_SUCCESS, $model];
    }


    public function update(int $id, array $data)
    {
        $admin = admin::where(['id' => $id, 'user_id' => $this->user['id'], 'status' => 0])
            ->save($data);
        return [HTTP_CREATED, $admin];
    }

    public function delete($id)
    {
        admin::destroy($id);
        return HTTP_NOCONTEND;
    }

}
